package com.guangjian.gjspring.common.dao;

import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.hibernate.Query;

public class BaseDaoImpl<T> implements BaseDao {

    @PersistenceContext
    private EntityManager em;

    public void persist(T t) {
        em.persist(t);
    }

    public T save(T t) {
        return em.merge(t);
    }

    public void delete(T t) {
        em.remove(t);
    }

    public T find(Class<T> clazz, Serializable id) {
        return em.getReference(clazz, id);
    }

    public List<T> find(String jpql) {
        return em.createQuery(jpql).getResultList();
    }

    public List<T> find(String jpql, Object param) {
        return em.createQuery(jpql).setParameter(1, param).getResultList();
    }

    public List<T> find(String jpql, Object[] param) {
        Query query = em.createQuery(jpql);
        for (int i = 1; i <= param.length; i++) {
            query.setParameter(i, param[i - 1]);
        }
        return query.getResultList();
    }

    public int findTotalCount(String jpql) {
        return ((Long) em.createQuery(jpql).getSingleResult()).intValue();
    }
}
